package demo;

import java.io.*;
import java.util.Objects;
import java.util.TreeSet;

//Day11
public class Day21003 {
    public static void main(String[] args) {
        TreeSet<Student03> set=new TreeSet<>();
        File file=new File("2.txt");
        try {
//            还原文件
            FileWriter writer=new FileWriter(file);
            writer.write("张三,19\n");
            writer.write("李四,17\n");
            writer.write("王五,23\n");
            writer.write("赵六,21");
            writer.close();
//            读取文件
            FileReader reader=new FileReader(file);
            BufferedReader bufferedReader=new BufferedReader(reader);
            for (int i=0;i<4;i++){
               String s= bufferedReader.readLine();
               String[] name=s.split(",");
               set.add(new Student03(name[0],Integer.parseInt(name[1])));
            }
            bufferedReader.close();
            reader.close();
//            调准顺序后写入
            FileWriter writer1=new FileWriter("2.txt");
            BufferedWriter bufferedWriter=new BufferedWriter(writer1);
            for (Student03 s:
                 set) {
                if(s!=set.last())
                    bufferedWriter.write(s.getName()+","+s.getAge()+"\n");
                else
                    bufferedWriter.write(s.getName()+","+s.getAge());
            }
            bufferedWriter.close();
            writer1.close();
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}
//学生类
class Student03 implements Comparable<Student03> {
    private String name;
    private Integer age;

    public Student03() {
    }

    public Student03(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student02{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    @Override
    public int compareTo(Student03 student03) {
        int result = this.getAge() - student03.getAge();
        if (result == 0)
            result = this.getName().compareTo(student03.getName());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (obj instanceof Student03) {
            if (this.getName().equals(((Student03) obj).getName()) && this.getAge() == ((Student03) obj).getAge())
                return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
